package com.cai310.lottery.ticket.protocol.local.utils;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cai310.lottery.Constant;
import com.cai310.lottery.common.Lottery;
import com.cai310.lottery.common.LotteryCategory;
import com.cai310.lottery.common.SalesMode;
import com.cai310.lottery.entity.lottery.Period;
import com.cai310.lottery.entity.lottery.ticket.Ticket;
import com.cai310.lottery.exception.DataException;
import com.cai310.lottery.prizeutils.template.VariableString;
import com.cai310.lottery.support.PrizeItem;
import com.cai310.lottery.ticket.common.HttpclientUtil;
import com.cai310.lottery.ticket.protocol.support.MessageSendDTO;
import com.cai310.lottery.ticket.protocol.support.TranCharset;
import com.cai310.lottery.utils.BigDecimalUtil;
import com.cai310.utils.DateUtil;
import com.cai310.utils.MD5;
import com.cai310.utils.UTF8PostMethod;

public abstract class CPUtil {
	public static final String SINGLE_SPACE = "+";
	private static final String reUrl="http://114.80.67.67:26828/PrintSystem3Motion.ashx/DealWith";
	private static final String key="123456";
	///获取开奖信息
	public String getReUrl(String reqIdValue,String msgIdValue,String peqParamValue){
		if(StringUtils.isBlank(reqIdValue))return null;
		if(StringUtils.isBlank(msgIdValue))return null;
		if(StringUtils.isBlank(peqParamValue))return null;
		StringBuffer sb = new StringBuffer();
		sb.append(reUrl);
		sb.append("?");
		sb.append("ReqId="+reqIdValue);
		sb.append("&");
		sb.append("MsgId="+msgIdValue);
		sb.append("&");
		sb.append("ReqParam="+peqParamValue);
		sb.append("&");
		sb.append("ReqKey="+MD5.md5(reqIdValue+msgIdValue+peqParamValue+key).toLowerCase());
		return sb.toString();	
	}
	public static void main(String[] args) throws ClientProtocolException, IOException, DocumentException {
		StringBuffer sb = new StringBuffer();
		sb.append("http://www.okooo.com/match/1/196688/odds/");
//
//		
		Map<String,String> ParamMap=new LinkedHashMap<String,String>();
//		ParamMap.put("OrderId", "13");
//		ParamMap.put("Mode", "1");
//		ParamMap.put("PeriodNumber", "2012018");
//		ParamMap.put("Cost", "8");
//		ParamMap.put("Multiple", "1");
//		ParamMap.put("Units", "4");
//		ParamMap.put("PlayType", "0");
//		ParamMap.put("Type", "");
//		ParamMap.put("PassType", "");
//		ParamMap.put("Value", "111111113333+333333331111+111111113333+333333331111");
//        
//        Document document = DocumentHelper.createDocument();
//	   	/** 建立XML文档的根 */
//	   	Element rootElement = document.addElement("ReqParam");
//	   	rootElement.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
//		rootElement.addAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
//		Element ticket = rootElement.addElement("Ticket");
//	   	for (String key : ParamMap.keySet()) {
//	   		String value = ParamMap.get(key);
//	   	    Element element = ticket.addElement(key);
//	   	    element.setText(value);
//		}
//  	    String  betValue =  "<?xml version=\"1.0\"?>"+rootElement.asXML();
//		
//		
//		Map<String,String> ParamMap1=new LinkedHashMap<String,String>();
//		String msgIdValue = System.currentTimeMillis()+"";
//		ParamMap1.put("ReqId", "801");
//		ParamMap1.put("LotteryId", "10");
//		ParamMap1.put("MsgId", msgIdValue);
//		ParamMap1.put("ReqParam", betValue);
//		ParamMap1.put("Uid", "14");
//		
//		ParamMap1.put("ReqKey", MD5.md5("801"+msgIdValue+"10"+"14"+betValue+"E10ADC3949BA59ABBE56E057F20F883E").toUpperCase());
		String returnString = HttpclientUtil.Utf8HttpClientUtils(sb.toString(),ParamMap);
//
//		Document doc=DocumentHelper.parseText(returnString);
		
		System.out.print(returnString);
		
		
		int i=0;
	}
	public CpResultVisitor sendTicket(Ticket ticket) throws DataException, IOException, DocumentException{
		String peqParamValue = buildPeqParamValue(ticket);
		String msgIdValue = System.currentTimeMillis()+""+ticket.getId();
		String reqIdValue = "801";
		
		Map<String,String> ParamMap=new LinkedHashMap<String,String>();
		ParamMap.put("ReqId", reqIdValue);
		ParamMap.put("MsgId", msgIdValue);
		ParamMap.put("ReqParam", peqParamValue);
		ParamMap.put("ReqKey", MD5.md5(reqIdValue+msgIdValue+peqParamValue+key).toLowerCase());
		
		String url = getReUrl(reqIdValue,msgIdValue,peqParamValue);
		
		String returnString = HttpclientUtil.Utf8HttpClientUtils(reUrl, ParamMap);
		Document doc=DocumentHelper.parseText(returnString);
		CpResultVisitor cpResultVisitor=new CpResultVisitor();
		doc.accept(cpResultVisitor);
		return cpResultVisitor;
	}
	public static QueryPVisitor confirmTicket(Ticket ticket) throws DataException, IOException, DocumentException{
		String msgIdValue = System.currentTimeMillis()+""+ticket.getId();
		String reqIdValue = "802";
		
		Map<String,String> ParamMap=new LinkedHashMap<String,String>();
		ParamMap.put("ReqId", reqIdValue);
		ParamMap.put("MsgId", msgIdValue);
		ParamMap.put("ReqParam", ""+ticket.getId());
		ParamMap.put("ReqKey", MD5.md5(reqIdValue+msgIdValue+ticket.getId()+key).toLowerCase());
		
		
		String returnString = HttpclientUtil.Utf8HttpClientUtils(reUrl, ParamMap);
		Document doc=DocumentHelper.parseText(returnString);
		QueryPVisitor queryPVisitor=new QueryPVisitor();
		doc.accept(queryPVisitor);
		return queryPVisitor;
	}
	public static QueryPVisitor updateTicketPrize(Ticket ticket) throws DataException, IOException, DocumentException{
		String msgIdValue = System.currentTimeMillis()+""+ticket.getId();
		String reqIdValue = "804";
		String peqParamValue = buildTicketPrizePeqParamValue(ticket);
		Map<String,String> ParamMap=new LinkedHashMap<String,String>();
		ParamMap.put("ReqId", reqIdValue);
		ParamMap.put("MsgId", msgIdValue);
		ParamMap.put("ReqParam", peqParamValue);
		ParamMap.put("ReqKey", MD5.md5(reqIdValue+msgIdValue+peqParamValue+key).toLowerCase());
		String returnString = HttpclientUtil.Utf8HttpClientUtils(reUrl, ParamMap);
		Document doc=DocumentHelper.parseText(returnString);
		QueryPVisitor queryPVisitor=new QueryPVisitor();
		doc.accept(queryPVisitor);
		return queryPVisitor;
	}
	
	/**
	 * 
	 * @param lottery
	 * @param playType
	 * @return
	 */
	public static String buildTicketPrizePeqParamValue(Ticket ticket){
		Map<String,String> ParamMap=new LinkedHashMap<String,String>();
		ParamMap.put("OrderId", ""+ticket.getId());
		ParamMap.put("Prize", ""+ticket.getTotalPrizeAfterTax());
		//ParamMap.put("PrizeDescription", ticket.getWonDetail());
		ParamMap.put("PrizeDescription", "");
        Document document = DocumentHelper.createDocument();
	   	/** 建立XML文档的根 */
	   	Element rootElement = document.addElement("ReqParam");
		Element ticketElement = rootElement.addElement("Ticket");
	   	for (String key : ParamMap.keySet()) {
	   		String value = ParamMap.get(key);
	   	    Element element = ticketElement.addElement(key);
	   	    element.setText(value);
		}
  	    return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+rootElement.asXML();
    }
	
	
	
	/**
	 * 
	 * @param lottery
	 * @param playType
	 * @return
	 */
	public String buildPeqParamValue(Ticket ticket){
		Lottery lottery = ticket.getLotteryType();
		Byte betType = ticket.getBetType();
		Map<String,String> ParamMap=new LinkedHashMap<String,String>();
		String OrderId=""+ticket.getId();
		ParamMap.put("OrderId", OrderId);
		ParamMap.put("SourceId", "1");
		ParamMap.put("Priority", "100");
		String PlatformId = getCpLotteryId(lottery,betType);
		ParamMap.put("PlatformId", PlatformId);
		String BetType = getCpBetType(ticket);
		ParamMap.put("BetType", BetType);
		if(ticket.getLotteryType().getCategory().equals(LotteryCategory.FREQUENT)){
			ParamMap.put("IssueNumber",getUpdatePeriodNumber(ticket));
		}else{
			ParamMap.put("IssueNumber", ticket.getPeriodNumber());
		}
		String EndSaleTime = DateUtil.dateToStr(ticket.getOfficialEndTime(),"yyyy/MM/dd HH:mm:ss");
		ParamMap.put("EndSaleTime", EndSaleTime);
		String PlayType = getCpPlayType(ticket);
		ParamMap.put("PlayType", PlayType);
		String Multiple = ""+ticket.getMultiple();
		ParamMap.put("Multiple", Multiple);
		String BetUnits = ""+ticket.getUnits();
		ParamMap.put("BetUnits", BetUnits);
		String BetCost = ""+ticket.getSchemeCost();
		ParamMap.put("BetCost", BetCost);
        String SpecialFlag = getSpecialFlag(ticket);
        ParamMap.put("SpecialFlag", SpecialFlag);
        String BetContent = getBetContent(ticket);
        ParamMap.put("BetContent", BetContent);
        ParamMap.put("MatchInfo", "");
        
        Document document = DocumentHelper.createDocument();
	   	/** 建立XML文档的根 */
	   	Element rootElement = document.addElement("ReqParam");
	   	rootElement.addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
		rootElement.addAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
	   	for (String key : ParamMap.keySet()) {
	   		String value = ParamMap.get(key);
	   	    Element element = rootElement.addElement(key);
	   	    element.setText(value);
		}
  	    return "<?xml version=\"1.0\"?>"+rootElement.asXML();
//		String localhostString= "<?xml version=\"1.0\"?>"+rootElement.asXML();
//		String zhengque = "<?xml version=\"1.0\"?><ReqParam xmlns:xsi=\" http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\" http://www.w3.org/2001/XMLSchema\"><OrderId>19615648</OrderId><PlatformId>3</PlatformId><BetType>0</BetType><IssueNumber>11055</IssueNumber><EndSaleTime>2011/5/29 23:00:00</EndSaleTime><PlayType>0</PlayType><Multiple>1</Multiple><BetUnits>1</BetUnits><BetCost>2</BetCost><SpecialFlag></SpecialFlag><BetContent>0,3,3,3,0,3,3,3,3,3,3,0,3,3</BetContent></ReqParam>";
//		
//		return "<?xml version=\"1.0\"?><ReqParam xmlns:xsi=\" http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\" http://www.w3.org/2001/XMLSchema\"><OrderId>19615648</OrderId><PlatformId>3</PlatformId><BetType>0</BetType><IssueNumber>11055</IssueNumber><EndSaleTime>2011/5/29 23:00:00</EndSaleTime><PlayType>0</PlayType><Multiple>1</Multiple><BetUnits>1</BetUnits><BetCost>2</BetCost><SpecialFlag></SpecialFlag><BetContent>0,3,3,3,0,3,3,3,3,3,3,0,3,3</BetContent></ReqParam>";
	}
	public static Ticket doUpdatePrize(List<PrizeItem> list,Ticket ticket) throws DataException {
		if (list == null || list.isEmpty()) {
			throw new DataException("中奖信息为空！");
		}

		BigDecimal totalPrize = BigDecimal.ZERO;// 总奖金
		BigDecimal totalPrizeAfterTax = BigDecimal.ZERO;// 税后总奖金

		VariableString varPrizeLineText = new VariableString(Constant.PRIZE_LINE_TMPLATE, null);

		StringBuilder sb = new StringBuilder();

		BigDecimal prizeAfterTax;
		for (PrizeItem item : list) {
			varPrizeLineText.setVar("PRIZENAME", item.getWinItem().getWinName());
			varPrizeLineText.setVar("WINUNITS", item.getWinItem().getWinUnit());
			varPrizeLineText.setVar("UNIT_PRIZE", Constant.numFmt.format(item.getUnitPrize()));
			prizeAfterTax = item.getUnitPrizeAfterTax();
			varPrizeLineText.setVar("UNIT_PRIZE_TAXED", Constant.numFmt.format(prizeAfterTax));
			sb.append(varPrizeLineText.toString());

			totalPrize = totalPrize.add(BigDecimalUtil.multiply(item.getUnitPrize(),
					BigDecimalUtil.valueOf(item.getWinItem().getWinUnit())));
			totalPrizeAfterTax = totalPrizeAfterTax.add(BigDecimalUtil.multiply(prizeAfterTax,
					BigDecimalUtil.valueOf(item.getWinItem().getWinUnit())));
		}

		 ticket.setTotalPrize(totalPrize.doubleValue());
		 ticket.setTotalPrizeAfterTax(totalPrizeAfterTax.doubleValue());
		 ticket.setWonDetail(sb.toString());
		 ticket.setWon(Boolean.TRUE);
		 ticket.setTicket_synchroned(Boolean.FALSE);
		 return ticket;
	}
	/**
	 *  
	 * @param lottery
	 * @param playType
	 * @return
	 */
	
	public abstract String getCpLotteryId(Lottery lottery,Byte betType);
	public abstract String getUpdatePeriodNumber(Ticket ticket);
	public abstract String getCpBetType(Ticket ticket);
	public abstract String getCpPlayType(Ticket ticket);
	public abstract String getBetContent(Ticket ticket);
	public abstract String getSpecialFlag(Ticket ticket);
	
}
